<template>
  <section class="todoapp">
    <hm-header @add="addItem"></hm-header>
    <hm-main
      :list="showList"
      @changeEvent="changeEvent"
      @allIn="allIn"
      @remove="remove"
    ></hm-main>
    <hm-footer
      :list="list"
      :status="status"
      @choice-status-event="status = $event"
      @clear-item-event="clearAll"
    ></hm-footer>
  </section>
</template>

<script>
const obj = {
  "#/": "all",
  "#/active": "active",
  "#/completed": "completed",
};
import HmHeader from "./components/hm-header.vue";
import HmMain from "./components/hm-main.vue";
import HmFooter from "./components/hm-footer.vue";
export default {
  components: {
    HmHeader,
    HmMain,
    HmFooter,
  },
  data() {
    return {
      list: JSON.parse(localStorage.getItem("list")) || [],
      status: obj[location.hash] || "all",
    };
  },
  methods: {
    changeEvent(id) {
      this.list.forEach((item) => {
        if (item.id === id) {
          item.flag = !item.flag;
        }
      });
    },
    allIn(value) {
      return this.list.filter((item) => (item.flag = value));
    },
    remove(id) {
      this.list = this.list.filter((item) => item.id !== id);
    },
    addItem(value) {
      const obj = { id: +new Date(), name: value, flag: false };
      this.list.push(obj);
    },
    clearAll() {
      this.list = this.list.filter((item) => !item.flag);
    },
  },
  watch: {
    list: {
      deep: true,
      handler(newValue) {
        localStorage.setItem("list", JSON.stringify(newValue));
      },
    },
  },
  computed: {
    showList() {
      if (this.status === "all") {
        return this.list;
      } else if (this.status === "active") {
        return this.list.filter((item) => !item.flag);
      } else {
        return this.list.filter((item) => item.flag);
      }
    },
  },
};
</script>

<style></style>